# -*- coding: utf-8 -*-
"""
#-------------------------------------------------------------------------------
# Nom:         affChroniques
#
# Auteur:      Alain Gauthier
#
# Créé le:     23/08/2013
# Copyright:   (c) eaucéa 2014
# Licence:     GNU Public Licence (GPL)

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

Affichage avec MatplotLib

#-------------------------------------------------------------------------------
"""

# modules système
import sys, os
# modules GUI
from PyQt4 import QtCore, QtGui
# modules externes
import numpy as np
import matplotlib
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar
from matplotlib.figure import Figure

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    _fromUtf8 = lambda s: s

#-------------------------------------------------------------------------------

class chroniqueMPL(QtGui.QDialog):
    """
    Classe d'affichage des chroniques selon les choix de l'utilisateur
    """

    #---------------------------------------------------------------------------

    def __init__(self, parent, AidBV, Aoptions, Atps, APluie, Aevapo, AQsim, AQmes):
        QtGui.QDialog.__init__(self, parent)

        matplotlib.rcParams['text.latex.unicode']=True

        titre=u'Débit simulé en '
        self.setWindowTitle(titre+AidBV)
        self.create_main_frame()

        self.options = Aoptions
        self.temps=Atps[:len(AQsim)]
        self.Pluie = APluie[:len(AQsim)]
        self.Evapo = Aevapo[:len(AQsim)]
        self.Qsim = AQsim
        self.Qmes = AQmes[:len(AQsim)]

        self.box=None

        self.on_draw()

    #---------------------------------------------------------------------------

    def save_plot(self):
        file_choices = "PNG (*.png)|*.png"

        path = unicode(QtGui.QFileDialog.getSaveFileName(self,
                        'Enregistrer sous', '',
                        file_choices))
        if path:
            self.canvas.print_figure(path, dpi=self.dpi)

    #---------------------------------------------------------------------------

    def on_about(self):
        msg = """ Affichage des chroniques de débit simulées avec le modèle
        pluie-débit à échelle régionale
        (c) eaucea- GNU General Public licence GPL
        """
        QtGui.QMessageBox.about(self, "A propos", _fromUtf8(msg.strip()))

    #---------------------------------------------------------------------------

    def on_pick(self, event):
        # The event received here is of the type
        # matplotlib.backend_bases.PickEvent
        #
        # It carries lots of information, of which we're using
        # only a small amount here.
        #
        box_points = event.artist.get_bbox().get_points()
        msg = "coordonnées :\n %s" % box_points

        QtGui.QMessageBox.information(self, "Click!", msg)

    #---------------------------------------------------------------------------

    def on_draw(self):
        """ Redraws the figure
        """
        # clear the axes and redraw the plot
        #
        self.axes.clear()
        self.axes.grid(self.grid_cb.isChecked())
        self.axes.set_ylabel(u'débit en $m^3/s$')

        # option[2]: Qsimulé
        labelmodele=u"modèle"
        labeldonnee=u"donnée"
        if self.options[2]:
            self.axes.plot(self.temps, self.Qsim,'r', linewidth=1,label=labelmodele)
        # option[3]: Qmesure
        if self.options[3]:
            self.axes.plot(self.temps[:len(self.Qmes)], self.Qmes,'b', linewidth=1,label=labeldonnee)

        # Shink current axis by 20%
        if self.box is None:
            self.box = self.axes.get_position()
        self.axes.set_position([self.box.x0, self.box.y0, self.box.width * 0.9, self.box.height])

        # légende
        self.axes.legend(loc='center left', bbox_to_anchor=(1, 0.5))
        # option[0]: pluie
        ax2 = self.axes.twinx()
        ax2.set_ylabel(u'pluie/évapotranspiration en mm')
        if self.options[0]:
            taille=np.min([len(self.temps),len(self.Pluie)])
            ax2.bar(self.temps[:taille],self.Pluie[:taille],width=15,color='g')
        # option[1]: evapo
        if self.options[1]:
            taille=np.min([len(self.temps),len(self.Evapo)])
            ax2.bar(self.temps[:taille],self.Evapo[:taille],width=15,color='y')
        ax2.invert_yaxis()

        self.canvas.draw()

    #---------------------------------------------------------------------------

    def create_main_frame(self):
        # Create the mpl Figure and FigCanvas objects.
        #
        self.fig = Figure()
        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self)

        # Since we have only one plot, we can use add_axes
        # instead of add_subplot, but then the subplot
        # configuration tool in the navigation toolbar wouldn't
        # work.
        #
        self.axes = self.fig.add_subplot(111)

        # Bind the 'pick' event for clicking on one of the bars
        #
        self.canvas.mpl_connect('pick_event', self.on_pick)

        # Create the navigation toolbar, tied to the canvas
        #
        self.mpl_toolbar = NavigationToolbar(self.canvas, self)

        # Other GUI controls
        #
        self.grid_cb = QtGui.QCheckBox("Afficher grille")
        self.grid_cb.setChecked(False)
        self.connect(self.grid_cb, QtCore.SIGNAL('stateChanged(int)'), self.on_draw)

        #
        # Layout with box sizers
        #
        hbox = QtGui.QHBoxLayout()
        hbox.addWidget(self.grid_cb)
        hbox.setAlignment(self.grid_cb, QtCore.Qt.AlignVCenter)

        vbox = QtGui.QVBoxLayout()
        vbox.addWidget(self.canvas)
        vbox.addWidget(self.mpl_toolbar)
        vbox.addLayout(hbox)

        self.setLayout(vbox)

    #---------------------------------------------------------------------------
    #---------------------------------------------------------------------------
